//
//  GoodsListViewController.m
//  TerritoryShopkeeper
//
//  Created by xiaowu on 2017/11/28.
//  Copyright © 2017年 ZDQK. All rights reserved.
//

#import "GoodsListViewController.h"
#import "GoodsListDoubleCell.h"
#import "GoodsListCommonCell.h"
#import "GoodsListModel.h"
#import "GoodsDetailViewController.h"
#import "FiltrateFirstView.h"
#import "GoodsListFiltrateModel.h"

typedef NS_ENUM(NSInteger, GoodsListShowType) {
    GoodsListShowTypeForCommon,
    GoodsListShowTypeForDouble
};

@interface GoodsListViewController () <UITableViewDataSource, UITableViewDelegate,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) UIButton *rightButton;

@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, assign) GoodsListShowType showType;
@property (nonatomic, strong) FiltrateFirstView *firstView;
@property (nonatomic, strong) GoodsListFiltrateModel *filtrateModel;

@end

@implementation GoodsListViewController

- (instancetype)init {
    self = [super init];
    if (self) {
        self.title = @"商品";
        _dataSource = [NSMutableArray array];
        _currentPage = 1;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self configureUI];
    
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [self loadNewData];
    
    [self responseBlock];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self hiddenShadowImage:NO];
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    self.firstView.frame = CGRectMake(0, 0, self.view.width, 44);
}

- (void)rightItemClick {
    if (self.showType == GoodsListShowTypeForCommon) {
        self.showType = GoodsListShowTypeForDouble;
        [self.rightButton setImage:[UIImage imageNamed:@"screen"] forState:UIControlStateNormal];
    } else {
        self.showType = GoodsListShowTypeForCommon;
        [self.rightButton setImage:[UIImage imageNamed:@"portrait"] forState:UIControlStateNormal];
    }
    [self.tableView reloadData];
}

#pragma mark - Method
- (void)configureUI {
    [self.view addSubview:self.firstView];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightButton];
    
    self.tableView.backgroundColor = [UIColor backgroundColor];
    [self.tableView clearExtendCellLine];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.emptyDataSetSource = self;
    self.tableView.emptyDataSetDelegate = self;
    [self.tableView registerNib:[UINib nibWithNibName:@"GoodsListCommonCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"commonCell"];
    [self.tableView registerClass:[GoodsListDoubleCell class] forCellReuseIdentifier:@"doubleCell"];
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.currentPage = 1;
        [weakSelf loadNewData];
    }];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.currentPage += 1;
        [weakSelf loadNewData];
    }];
}
- (void)responseBlock {
    __weak typeof(self) weakSelf = self;
    self.firstView.block = ^(NSInteger index) {
        switch (index) {
            case 0: {
                // 推荐
                weakSelf.filtrateModel.sort = @"1";
                [weakSelf loadNewData];
            } break;
            case 1: {
                // 销量
                weakSelf.filtrateModel.sort = @"2";
                [weakSelf loadNewData];
            } break;
            case 3: {
                // 筛选
                
            } break;
            case 4: {
                // 升序
                weakSelf.filtrateModel.sort = @"3";
                [weakSelf loadNewData];
            } break;
            case 5: {
                // 降序
                weakSelf.filtrateModel.sort = @"4";
                [weakSelf loadNewData];
            } break;
            default:
                break;
        }
    };
}
#pragma mark - NetWork
- (void)loadNewData {
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:@(self.currentPage) forKey:@"pageNumber"];
    [parameters setObject:PageSize forKey:@"pageSize"];
    
    [parameters setObject:self.filtrateModel.sort forKey:@"sort"]; // 排序(1推荐2销量3价格升4价格降)
    
//    FiltrateSecondModel *model1 = [self.secondArr objectAtIndex:0];
//    FiltrateSecondModel *model2 = [self.secondArr objectAtIndex:1];
//    FiltrateSecondModel *model3 = [self.secondArr objectAtIndex:2];
//    FiltrateSecondModel *model4 = [self.secondArr objectAtIndex:3];
    
    [parameters setObject:self.filtrateModel.isrecommend forKey:@"isrecommend"]; // 是否推荐(1是0否)
    [parameters setObject:self.filtrateModel.issalesvolume forKey:@"issalesvolume"]; // 销量(1是0否)
    [parameters setObject:self.filtrateModel.isprice forKey:@"isprice"]; // 价格(0否1升序2降序)
    [parameters setObject:@"0" forKey:@"isnew"];   // 是否新品(1是0否)
    [parameters setObject:@"0" forKey:@"isdiscount"]; // 是否优惠劵(1是0否)
    [parameters setObject:@"0" forKey:@"ispromotion"]; // 是否促销(1是0否)
    [parameters setObject:@"0" forKey:@"isfreeshipping"]; // 是否包邮(1是0否)
    [parameters setObject:self.gcid forKey:@"gcid"];     // 一级分类id集合
    [parameters setObject:self.gtcid forKey:@"gtcid"];    // 二级分类id集合
    [parameters setObject:self.gtrcid forKey:@"gtrcid"];    // 二级分类id集合
    [parameters setObject:@"" forKey:@"pricemin"]; // 价格1
    [parameters setObject:@"" forKey:@"pricemax"]; // 价格2

    __weak typeof(self) weakSelf = self;
    [MYAFNetworking POST:URL_Get_Goods_List parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        [weakSelf.tableView.mj_header endRefreshing];
        [weakSelf.tableView.mj_footer endRefreshing];
        NSDictionary *responseDic = responseObject;
        NSString *code = [responseDic safeStringForKey:@"code"];
        
        if (code && [code isEqualToString:@"200"]) {
            
            NSDictionary *data = [responseDic safeJsonObjectForKey:@"data"];
            NSArray *list = [data safeJsonObjectForKey:@"list"];
            NSString *totalPage = [data safeObjectForKey:@"totalPage"];
            if (weakSelf.currentPage == totalPage.integerValue || totalPage.integerValue == 0) {
                [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                [weakSelf.tableView.mj_footer setHidden:YES];
            } else {
                [weakSelf.tableView.mj_footer resetNoMoreData];
                [weakSelf.tableView.mj_footer setHidden:NO];
            }
            
            if (weakSelf.currentPage == 1) {
                [weakSelf.dataSource removeAllObjects];
            }
            
            for (NSDictionary *modelDic in list) {
                GoodsListModel *model = [GoodsListModel mj_objectWithKeyValues:modelDic];
                [weakSelf.dataSource addObject:model];
            }
            
            [weakSelf.tableView reloadData];
            
        } else {
            [MBProgressHUD showError:weakSelf.view title:[responseDic safeStringForKey:@"message"] code:code animated:YES];
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        [MBProgressHUD showError:weakSelf.view title:@"" code:@"" animated:YES];
    }];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.showType == GoodsListShowTypeForCommon) {
        return self.dataSource.count;
    } else {
        return [GoodsListDoubleCell getRowNumberWithItemArr:self.dataSource];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.showType == GoodsListShowTypeForCommon) {
        GoodsListCommonCell *commonCell = [tableView dequeueReusableCellWithIdentifier:@"commonCell" forIndexPath:indexPath];
        GoodsListModel *model = [self.dataSource objectAtIndex:indexPath.row];
        [commonCell setValueForCellWithModel:model];
        return commonCell;
    } else {
        GoodsListDoubleCell *doubleCell = [tableView dequeueReusableCellWithIdentifier:@"doubleCell" forIndexPath:indexPath];
        NSArray *arr =  [GoodsListDoubleCell getCellItemArr:self.dataSource withIndexPath:indexPath];
        [doubleCell setValuesForCellWithItems:arr];
        
        __weak typeof(self) weakSelf = self;
        doubleCell.block = ^(NSInteger index) {
            GoodsListModel *model = [arr objectAtIndex:index];
            if (!model.isshelves) {
                [MBProgressHUD showError:weakSelf.view title:@"该商品已下架" code:@"" animated:YES];
                return;
            }
            GoodsDetailViewController *detailVC = [[GoodsDetailViewController alloc] init];
            detailVC.gid = model.gid;
            [weakSelf.navigationController pushViewController:detailVC animated:YES];
        };
        return doubleCell;
    }
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.showType == GoodsListShowTypeForCommon) {
        return [GoodsListCommonCell getHeight];
    } else {
        return [GoodsListDoubleCell getHeight];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (self.showType == GoodsListShowTypeForCommon) {
        GoodsListModel *model = [self.dataSource objectAtIndex:indexPath.row];
        if (!model.isshelves) {
            [MBProgressHUD showError:self.view title:@"该商品已下架" code:@"" animated:YES];
            return;
        }
        GoodsDetailViewController *detailVC = [[GoodsDetailViewController alloc] init];
        detailVC.gid = model.gid;
        [self.navigationController pushViewController:detailVC animated:YES];
    }
}

#pragma mark - DZNEmptyDataSetSource, DZNEmptyDataSetDelegate
//主提示标题
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    return [[NSAttributedString alloc] initWithString:@"暂无商品"
                                           attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:16.0],
                                                        NSForegroundColorAttributeName:[UIColor grayTextColor]}];
}
- (void)emptyDataSet:(UIScrollView *)scrollView didTapView:(UIView *)view {
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [self loadNewData];
}

#pragma mark - Getters
- (UIButton *)rightButton {
    if (!_rightButton) {
        _rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_rightButton addTarget:self action:@selector(rightItemClick) forControlEvents:UIControlEventTouchUpInside];
        [_rightButton setImage:[UIImage imageNamed:@"portrait"] forState:UIControlStateNormal];
    }
    return _rightButton;
}
- (FiltrateFirstView *)firstView {
    if (!_firstView) {
        _firstView = [[FiltrateFirstView alloc] initWithType:FiltrateTypeThree];
    }
    return _firstView;
}
- (GoodsListFiltrateModel *)filtrateModel {
    if (!_filtrateModel) {
        _filtrateModel = [[GoodsListFiltrateModel alloc] init];
    }
    return _filtrateModel;
}

@end
